//
//  ProfilePopController.swift
//  MoyoungMy
//
//  Created by 易先生 on 2022/8/13.
//

import UIKit
import MYModule
import RxCocoa


class ProfilePopController: ViewController {

    public var showType: ProfileType = .none

	public let itemValueChange = BehaviorRelay<Bool>(value: false)
   
    init(showType: ProfileType) {
        super.init(nibName: nil, bundle: nil)

//        self.modalTransitionStyle = .crossDissolve
        self.modalPresentationStyle = .overCurrentContext
        self.view.backgroundColor = .black.withAlphaComponent(0.1)
        self.showType = showType
        reloadPickerView()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
	override func viewDidLoad() {
		super.viewDidLoad()

	}

	override func viewDidAppear(_ animated: Bool) {
		super.viewDidAppear(true)
	}

	override func makeUI() {
		super.makeUI()
        view.addSubview(pickerView)
        view.addSubview(datePickerBgView)
        datePickerBgView.addSubview(datePicker)
        view.addSubview(topView)
		topView.addSubview(cancelButton)
		topView.addSubview(doneButton)
		topView.addSubview(lineView)
        
       
		pickerView.snp.makeConstraints { make in
			make.leading.trailing.bottom.equalToSuperview()
			make.height.equalTo(216)
		}
        
        datePickerBgView.snp.makeConstraints { make in
            make.leading.trailing.bottom.equalToSuperview()
            make.height.equalTo(216)
        }
        
        datePicker.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }

		topView.snp.makeConstraints { make in
            make.bottom.equalTo(pickerView.snp.top)
			make.leading.trailing.equalToSuperview()
			make.height.equalTo(45)
		}

		cancelButton.snp.makeConstraints { make in
			make.leading.top.bottom.equalToSuperview()
			make.width.equalTo(100)
		}

		doneButton.snp.makeConstraints { make in
			make.top.trailing.bottom.equalToSuperview()
			make.width.equalTo(100)
		}

		lineView.snp.makeConstraints { make in
			make.leading.trailing.bottom.equalToSuperview()
			make.height.equalTo(1)
		}
	}
    
	private func reloadPickerView() {

        let profile = UserCacheManagement.userInfo()
        
        guard showType == .birth else {
            datePickerBgView.isHidden = true
            let defaultHeightCm = profile.sex == .male ? 175 : 160
            let defaultWeightKg = profile.sex == .male ? 65 : 50
            
            switch showType {
            case .sex:
                pickerView.selectRow(profile.sex.rawValue, inComponent: 0, animated: false)
            case .height:
                var selected = 0
                if profile.unitType == .metric {
                    selected = (profile.height == 0 ? defaultHeightCm : profile.height) - heights.first!
                } else {
                    selected = (profile.height == 0 ? Unit.sharedInstance.convertIn(defaultHeightCm) : profile.height) - heightIns.first!
                }
                pickerView.selectRow(selected, inComponent: 0, animated: false)
            case .weight:
                var selected = 0
                if profile.unitType == .metric {
                    selected = (profile.weight == 0 ? defaultWeightKg : profile.weight) - weights.first!

                } else {
                    selected = (profile.weight == 0 ? Unit.sharedInstance.convertLb(defaultWeightKg) : profile.weight) - weightIns.first!
                }
                pickerView.selectRow(selected, inComponent: 0, animated: false)
            case .birth:
                let timeFormatter = DateFormatter()
                timeFormatter.locale = myLocal
                timeFormatter.dateFormat = "yyyy"
                timeFormatter.calendar = Calendar.init(identifier: .gregorian)
                let nowYear = Int(timeFormatter.string(from: Date()))!

                let birth = (profile.birth == 0 ? 1990 : profile.birth)
                pickerView.selectRow(nowYear - birth, inComponent: 0, animated: false)
            case .steplength:
                var selected = 0
                if profile.unitType == .metric {
                    selected = (profile.steplength == 0 ? 83 : profile.steplength) - 30
                } else {
                    selected = (profile.steplength == 0 ? 33 : profile.steplength) - 12
                }
                pickerView.selectRow(selected, inComponent: 0, animated: false)
            case .until:
                let selected = profile.unitType == .metric ? 0 : 1
                pickerView.selectRow(selected, inComponent: 0, animated: false)
            case .heartMax:
                let selected = (profile.warningMxHR == 0 ? 220 : profile.warningMxHR) - 60
                pickerView.selectRow(selected, inComponent: 0, animated: false)
            case .none:
                break
            }
            return
        }
        pickerView.isHidden = true
        let date = Date(timeIntervalSince1970: TimeInterval(profile.birth))
        datePicker.setDate(date, animated: true)
    }

	@objc private func cancelAction() {
		self.dismiss(animated: true)
	}

	@objc private func doneAction() {
		self.dismiss(animated: true)

        var profile = UserCacheManagement.userInfo()

		let selected = pickerView.selectedRow(inComponent: 0)
        
        let defaultHeightCm = profile.sex == .male ? 175 : 160
        let defaultWeightKg = profile.sex == .male ? 65 : 50

		switch showType {
		case .sex:
            profile.sex = UserModel.Sex(rawValue: selected)!
		case .height:
            if profile.unitType == .metric {
                profile.height = heights[selected]
            } else {
                profile.height = heightIns[selected]
            }
           
		case .weight:
            if profile.unitType == .metric {
                profile.weight = weights[selected]
            } else {
                profile.weight = weightIns[selected]
            }
		case .birth:
            profile.birth = Int(datePicker.date.timeIntervalSince1970)
        case .steplength:
            if profile.unitType == .metric {
                profile.steplength = 30 + selected
            } else {
                profile.steplength = 12 + selected
            }
        case .until:
            profile.unitType = untiles[selected]
            profile.sex = .male
            profile.height = profile.unitType == .metric ? defaultHeightCm : Unit.sharedInstance.convertIn(defaultHeightCm)
            profile.weight = profile.unitType == .metric ? defaultWeightKg : Unit.sharedInstance.convertLb(defaultWeightKg)
//            profile.birth = nowYear - 20
            profile.steplength = profile.unitType == .metric ? 83 : 33
        case .heartMax:
            profile.warningMxHR = hrMaxs[selected]
        case .none:
            break
        }
        UserCacheManagement.updateUserInfo(profile)
		itemValueChange.accept(true)
	}

	override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
		cancelAction()
	}
    
    private func fromHeigthGetStepLength(height: Int) -> Int {
        let profile = UserCacheManagement.userInfo()
        var heightMetric = height
        if profile.unitType == .imperial {
            heightMetric = lround(Double(height) * 2.54)
        }
        var stepLength = 83
        if heightMetric >= 175 {
            stepLength = (heightMetric - 8) >> 1
        } else if heightMetric <= 156 {
            stepLength = (heightMetric - 16) >> 1
        } else {
            stepLength = (heightMetric - 12) >> 1
        }
        stepLength = lround(Double(stepLength) * 0.85)
        if profile.unitType == .imperial {
            stepLength = lround(Double(stepLength) * 0.3937)
        }
        if profile.unitType == .metric {
            if stepLength < 30 {
                stepLength = 30
            }
            if stepLength > 155 {
                stepLength = 155
            }

        } else {
            if stepLength < 12 {
                stepLength = 12
            }
            if stepLength > 60 {
                stepLength = 60
            }

        }
        return stepLength
    }

	private lazy var topView: View = {
		let topView = View()
        topView.backgroundColor = UIColor.background
		return topView
	}()

	private lazy var cancelButton: Button = {
		let cancelButton = Button()
		cancelButton.setTitleColor(UIColor.assist_222222, for: .normal)
		cancelButton.setTitle("page_cancel".language, for: .normal)
		cancelButton.titleLabel?.font = Fonts.systemFont(ofSize: 16)
		cancelButton.addTarget(self, action: #selector(cancelAction), for: .touchUpInside)
		return cancelButton
	}()

	private lazy var doneButton: Button = {
		let doneButton = Button()
		doneButton.setTitleColor(UIColor.assist_222222, for: .normal)
		doneButton.setTitle("dialog_finished".language, for: .normal)
		doneButton.titleLabel?.font = Fonts.systemFont(ofSize: 16)
		doneButton.addTarget(self, action: #selector(doneAction), for: .touchUpInside)
		return doneButton
	}()

	private lazy var lineView: View = {
		let lineView = View()
		lineView.backgroundColor = UIColor.assist_D0D0D0
		return lineView
	}()

    private let datePickerBgView: View = {
        let view = View()
        view.backgroundColor = .white
        return view
    }()
    
    private lazy var datePicker: UIDatePicker = {
        let datePicker = UIDatePicker()

        datePicker.backgroundColor = UIColor.background

        datePicker.datePickerMode = .date;
        datePicker.minimumDate = "1900-01-01".toDate()?.date
        datePicker.maximumDate = Date()
        if #available(iOS 13.4, *) {
            datePicker.preferredDatePickerStyle = .wheels
        } else {
            // Fallback on earlier versions
        }
        return datePicker
    }()
    
	private lazy var pickerView: UIPickerView = {
		let pickerView = UIPickerView()
        pickerView.backgroundColor = UIColor.background
		pickerView.delegate = self
		pickerView.dataSource = self
		return pickerView
	}()

    var sexs: [String] = UserCacheManagement.userInfo().sexs

	var years: [Int] = {
		let date = Date()
		let timeFormatter = DateFormatter()
		timeFormatter.locale = myLocal
		timeFormatter.dateFormat = "yyyy"
		timeFormatter.calendar = Calendar.init(identifier: .gregorian)
		let nowYear = Int(timeFormatter.string(from: date))!
		var nums: [Int] = []
		for index in 0...100 {
			nums.append(nowYear - index)
		}
		return nums
	}()

    var heights = [Int](90...245)
    
    var heightIns = [Int](36...96)

    var weights = [Int](20...200)
    
    var weightIns = [Int](44...440)
    
    var hrMaxs = [Int](60...220)

    var stepLengths = [Int](30...155)

    var stepLengthIms = [Int](12...60)
    
    var untiles = UnitType.allCases
    
	var heightUnits = ["unit_cm".language, "in"]
	var weightUnits = ["unit_kg".language, "lb"]
}

extension ProfilePopController: UIPickerViewDelegate, UIPickerViewDataSource {

	func numberOfComponents(in pickerView: UIPickerView) -> Int {
        if getCurrentLanguage() != .chinese &&
            (showType == .weight ||
             showType == .height ||
             showType == .steplength) {
			return 2
		}
		return 1
	}

	func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        let profile = UserCacheManagement.userInfo()
		if component == 0 {
			switch showType {
			case .sex:
				return sexs.count
			case .height:
                return profile.unitType == .metric ? heights.count : heightIns.count
			case .weight:
                return profile.unitType == .metric ? weights.count : weightIns.count
			case .birth:
				return years.count
            case .steplength:
                if profile.unitType == .metric {
                    return stepLengths.count
                } else {
                    return stepLengthIms.count
                }
            case .until:
                return untiles.count
            case .heartMax:
                return hrMaxs.count
            case .none:
                break
            }
		}
		return 1
	}

	func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        let profile = UserCacheManagement.userInfo()
		if component == 0 {
			switch showType {
			case .sex:
				return "\(sexs[row])"
			case .height:
                return profile.unitType == .metric ? "\(heights[row])" : "\(heightIns[row])"
			case .weight:
				return profile.unitType == .metric ? "\(weights[row])" : "\(weightIns[row])"
			case .birth:
				return "\(years[row])"
            case .steplength:
                if profile.unitType == .metric {
                    return "\(stepLengths[row])"
                } else {
                    return "\(stepLengthIms[row])"
                }
            case .until:
                return untiles[row].localeName
            case .heartMax:
                return "\(hrMaxs[row])"
            case .none:
                return ""
            }
		} else {
            let unitType = profile.unitType
			if showType == .weight {
                if unitType == .metric {
					return String(weightUnits[0])
				} else {
					return String(weightUnits[1])
				}
			} else {
				if unitType == .metric {
					return String(heightUnits[0])
				} else {
					return String(heightUnits[1])
				}
			}
		}
	}

	func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        
        

	}

}
